#include <iostream>
#include <unistd.h>
#include <pthread.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <map>
using namespace std;
// tcp测试版
// 序列化和反序列化
//网络版计算器的实现
int main(int argc, char *argv[])
{
    // 创建套接字
    int sock = socket(AF_INET, SOCK_STREAM, 0);
    if (sock < 0)
    {
        cout << "sock enrro" << endl;
        exit(1);
    }
    // 绑定
    sockaddr_in local;
    memset(&local, 0, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(atoi(argv[2]));
    local.sin_addr.s_addr = inet_addr(argv[1]);
    int ret = bind(sock, (sockaddr *)&local, sizeof(local));
    if (ret < 0)
    {
        cout << "bind enrro" << endl;
        exit(2);
    }
    // 监听
    int listens = listen(sock, 20);
    if (listens < 0)
    {
        cout << "listen enrro" << endl;
        exit(3);
    }
    char buffer[1024];
    memset(buffer, 0, sizeof(buffer));
    // 连接
    sockaddr_in client;
    socklen_t len = sizeof(client);
    int servesock = accept(sock, (sockaddr *)&client, &len);
    while (true)
    {
        ssize_t s = read(servesock, buffer, 1023);
        if (s > 0)
        {
            buffer[s] = '\0';
            cout << buffer << endl;
            write(servesock, buffer, 1024);
            memset(buffer, 0, sizeof(buffer));
            // close(servesock);
        }
        if (s <= 0)
            break;
    }

    return 0;
}
